package com.itheima.tanhua.service;

import com.alibaba.fastjson.JSON;
import com.itheima.tanhua.dto.UserFreezeDto;
import com.itheima.tanhua.exception.BusinessException;
import com.itheima.tanhua.utils.Constants;
import com.itheima.tanhua.vo.ErrorResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Lff
 * @date 2022/4/6
 * <p>
 * 检验用户的账号状态
 */
@Service
public class UserFreezeService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户是否被冻结
     * 用户id
     *
     * @param status
     * @param userId
     */
    public void checkUserStatus(String status, Long userId) {
        //拼接key
        String key = Constants.USER_FREEZE + userId;
        /**
         * 获取过期时间
         * -1-永久
         * -2-不存在
         * 返回剩余时间 -存在
         */
        Long expire = redisTemplate.opsForValue().getOperations().getExpire(key);
        //获取
        String s = (String) redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(s)) {
            return;
        }
        UserFreezeDto dto = JSON.parseObject(s, UserFreezeDto.class);
        if (expire == -1 && status.equals(dto
                .getFreezingRange())) {
            throw new BusinessException(ErrorResult.builder().errMessage("账号已被永久封禁").build());
        } else if (expire > 0 && status.equals(dto
                .getFreezingRange() + "")) {
            long l = System.currentTimeMillis() + expire * 1000;
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(l));
            throw new BusinessException(ErrorResult.builder().errMessage("账号已被封禁到" + format).build());
        }
    }
}
